﻿using LanqiQAwebapi.Models;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System;
using LanqiQAwebapi.Interface;
namespace LanqiQAwebapi.Todo
{
    public class jwt : Ijwt
    {
        private readonly IConfiguration _configuration;

        public jwt(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        //生成RefreshToken
        public string RefreshTokenAsync(string userid, string username, string AccessToken, string role)
        {
            //
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            try
            {
                JwtSecurityToken jwtToken = handler.ReadJwtToken(AccessToken);
                if (jwtToken.Claims.Any(claim => claim.Type == JwtRegisteredClaimNames.Exp))
                {
                    long expUnixTimeSeconds = long.Parse(jwtToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Exp).Value);
                    DateTime expiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expUnixTimeSeconds);
                    if (DateTime.UtcNow > expiration)
                    {
                        return GetToken(username, userid, role);
                    }
                }
            }
            catch (Exception ex)
            {

                return "eeor";
            }
            return "";


        }
        //检查token并刷新token
        //长期token没过过期。短期token 过期，颁发新的Accesstoken
        public string AccessTokenAsync(string userid, string username)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
             new Claim(ClaimTypes.Name, username),
             new Claim(ClaimTypes.Role, "AccessToken"),
             new Claim(ClaimTypes.Sid, userid),
               };

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],
                _configuration["Jwt:Audience"],
                claims,
                DateTime.Now,
                DateTime.Now.AddHours(168),
                signingCredentials
            );
            try
            {
                var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                return token;
            }
            catch (Exception e)
            {

                return "";
            }
        }
        /// <summary>
        /// 生成Accesstoken
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        private string GetToken(string username, string userid)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {

             new Claim(ClaimTypes.Name, username),
             new Claim(ClaimTypes.Role, "AccessToken"),
             new Claim(ClaimTypes.Sid, userid),

               };


            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],
                _configuration["Jwt:Audience"],
                claims,
                DateTime.Now,
                DateTime.Now.AddDays(6),
                signingCredentials
            );



            try
            {
                var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                return token;
            }
            catch (Exception e)
            {

                return e.Message;
            }



        }

        /// <summary>
        /// 生成RefreshToken
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        private string GetToken(string username, string userid, string role)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
             new Claim(ClaimTypes.Name, username),
             new Claim(ClaimTypes.Role, role),
             new Claim(ClaimTypes.Sid, userid),

               };
            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],
                _configuration["Jwt:Audience"],
                claims,
                DateTime.Now,
                DateTime.Now.AddHours(1),
                signingCredentials
            );
            try
            {
                var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                return token;
            }
            catch (Exception e)
            {

                return "error";
            }
        }

    }
}
